package com.alt.ui;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alt.R;
import com.alt.base.ALTBaseActivity;
import com.alt.handler.CMCmdHandler;
import com.alt.manager.ALTAppMgr;
import com.alt.manager.ALTPTCMgr;
import com.alt.manager.ALTPTCMgr.SCREEN_UI;
import com.alt.models.UserData2;
import com.alt.models.UserLogInfo;
import com.alt.shared.onImageSet;
import com.alt.utils.ALTSysUtils;

public class ALTEditAvartar extends ALTBaseActivity implements OnClickListener {
	private ImageView imgAvartar;
	private Button btnEdit;
	private Button btnSave;
	private TextView tvNameUser;
	private String strPhotoType;
	private byte[] byteArray;
	private boolean isClick = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_avartar_layout);
		onSetScreenMode(SCREEN_UI.EDITPROFILE);
		imgAvartar = (ImageView) findViewById(R.id.imgAvartar);
		tvNameUser = (TextView) findViewById(R.id.tvNameUser);

		btnEdit = (Button) findViewById(R.id.btnEdit);
		btnSave = (Button) findViewById(R.id.btnSave);
		initData();
	}

	private void initData() {
		if (ALTAppMgr.isChangeAvarta) {
			imgAvartar.setImageBitmap(ALTSysUtils.byte2bitmap(ALTAppMgr.getInstance().getUserLogInfoModel().getImage()));
		} else {
			if(ALTAppMgr.getInstance().getUserLogInfo().AvatarData.length!=0)
			imgAvartar.setImageBitmap(ALTSysUtils.byte2bitmap(ALTAppMgr.getInstance().getUserLogInfo().AvatarData));
		}

		tvNameUser.setText(ALTAppMgr.getInstance().getUserLogInfo().Username);
		btnEdit.setOnClickListener(this);
		btnSave.setOnClickListener(this);

	}

	@SuppressWarnings("unused")
	public void onClick(View v) {
		Intent intent = null;
		int requestCode = 0;
		if (v == btnEdit) {
			getPicture();
		}
		if (v == btnSave) {
			if (isClick) {
				
				if(byteArray.length >= 6000){
					alert("image is too large!");
					return;
				}
				
				UserLogInfo uData = ALTAppMgr.getInstance().getUserLogInfo();
				UserData2 uData2 = new UserData2();
				uData2.UserId = uData.UserId;
				uData2.Username = uData.Username;
				uData2.AvatarId = uData.AvatarId;
//				uData2.AvatarId = "8";
				Log.v("HAI", uData2.AvatarId+" is avarta ID");
				uData2.Password = uData.Password;
				uData2.TotalUserFee = uData.TotalUserFee;

				uData2.AvatarData = ALTSysUtils.encodeImage(byteArray);

				Bundle b = new Bundle();
				b.putSerializable(ALTPTCMgr.REST_OBJECT_PUT, uData2);
				ALTAppMgr.getInstance().startServiceCmd(CMCmdHandler.COMMAND_UPDATE_PROFILE_PICTURE, new CMCmdHandler(), b, true);
				isClick = false;
			}

		}
		if (null != intent) {
			getParent().startActivityForResult(intent, requestCode);
		}

	}

	private void getPicture() {
		ALTEditAvartar.this.startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), 10);
	}

	@Override
	protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// Log.v("HAI", "ghgfh");
		if (resultCode == RESULT_OK) {
			if (requestCode == 10) {
				try {
					Uri selectedImageUri = data.getData();
					String selectedImagePath = getPath(selectedImageUri);
					((onImageSet) this).setimage(selectedImageUri, selectedImagePath);
				} catch (Exception e) {
					e.printStackTrace();
					this.calldialog();
				}
			}
		}
	}

	private String getPath(final Uri uri) {

		String[] projection = { MediaStore.Images.Media.DATA };

		Cursor cursor = this.managedQuery(uri, projection, null, null, null);

		int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

		cursor.moveToFirst();

		return cursor.getString(columnIndex);

	}

	/**
	 * Calldialog.
	 */
	private void calldialog() {
		AlertDialog.Builder builder;
		builder = new AlertDialog.Builder(this);
		builder.setMessage("Your Selection is not a photo").setNeutralButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialog, final int id) {
				// Do nothing.\

			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	// Read bitmap
	private Bitmap getBitmapFromURI(Context cont, Uri selectedImage) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inSampleSize = 4;
		Bitmap bm = null;
		AssetFileDescriptor fileDescriptor = null;
		try {
			fileDescriptor = cont.getContentResolver().openAssetFileDescriptor(selectedImage, "r");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, opt);
				fileDescriptor.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bm;
	}

	@Override
	public void setimage(Uri selectedImageUri, String path) {
		
		// int[] limitlst = {20, 15, 10 , 5};
		
		try {
			this.strPhotoType = path.toString().substring(path.toString().lastIndexOf(".") + 1, path.toString().length());
			Bitmap bitmap = null;
			if (selectedImageUri != null) {
				bitmap = getBitmapFromURI(this, selectedImageUri);
			} else {
				File imgFile = new File(path);
				bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
			}
			Bitmap reSize = getResizedBitmap(bitmap, 210, 210);
			imgAvartar.setImageBitmap(reSize);
			isClick = true;
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			reSize.compress(Bitmap.CompressFormat.JPEG, 20 , stream);
			byteArray = stream.toByteArray();	
			
//			//limit 8192 byte ~ 8KB
//			for (int i = limitlst.length-1; i >= 0; i--) {
//				if(byteArray.length >= 6000){
//					reSize.compress(Bitmap.CompressFormat.JPEG, limitlst[i], stream);
//					byteArray = stream.toByteArray();					
//				}else{
//					break;
//				}
//			}
			
//			Toast.makeText(this, String.valueOf(byteArray.length), Toast.LENGTH_LONG).show();
			
		} catch (Exception e) {
			System.out.println(e);
			e.printStackTrace();
		}

	}

	private Bitmap getResizedBitmap(final Bitmap bm, final int newHeight, final int newWidth) {

		if (bm == null) {
			return null;
		}
		int width = bm.getWidth();
		int height = bm.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// CREATE A MATRIX FOR THE MANIPULATION
		Matrix matrix = new Matrix();
		// RESIZE THE BIT MAP
		matrix.postScale(scaleWidth, scaleHeight);
		// RECREATE THE NEW BITMAP
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
		return resizedBitmap;
	}

	@Override
	public void processCommandResult(int commandCode, Object resultData) {
		// TODO Auto-generated method stub
		super.processCommandResult(commandCode, resultData);

		Bundle bResult = (Bundle) resultData;

		switch (commandCode) {

		case CMCmdHandler.COMMAND_UPDATE_PROFILE_PICTURE: {
			String value = bResult.getString(ALTPTCMgr.REST_OBJECT_RETURN);
			try {
				String valueReplace = value.replaceAll("\"", "");
				int valueInt = Integer.valueOf(valueReplace);
				if (1 == valueInt) {
					ALTAppMgr.isChangeAvarta = true;
					ALTAppMgr.getInstance().getUserLogInfoModel().setImage(byteArray);
					showDialogConfirm(this, getString(R.string.txt_update_success));
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

		}
			break;

		default:
			break;
		}
	}

	private void showDialogConfirm(final Context context, final String message) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(getString(R.string.txt_app_exit));
		builder.setMessage(message).setNeutralButton(getString(R.string.str_dongy), new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				finish();

			}
		});
		AlertDialog alert = builder.create();
		alert.setCancelable(false);
		alert.setCanceledOnTouchOutside(false);
		alert.show();
	}

}
